package cz.none.bezbarier.web.util;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;

import cz.none.bezbarier.web.model.Role;
import cz.none.bezbarier.web.model.User;
import cz.none.bezbarier.web.repository.UserRepository;
import cz.none.bezbarier.web.security.StaticSaltSource;

/**
 * This class is for initialization of DB and populating it with startup data.
 *
 * @author masoukup
 *
 */
@Service
public class DBInitializeBean implements InitializingBean {

	@Autowired
	private UserRepository repository;

	@Autowired
	private PasswordEncoder encoder;

	@Autowired
	private StaticSaltSource saltSource;

	@Override
	public void afterPropertiesSet() throws Exception {
		if (repository.count() == 0) {
			User user = new User();
			user.setEmail("a@a.cz");
			user.setPassword(encoder.encodePassword("test", saltSource.getSalt(null)));
			user.setName("admin");
			user.setSurname("ADMIN");
			user.setActive(true);
			user.setLocked(false);
			user.setRole(Role.ADMIN);

			repository.save(user);
		}

	}

}
